package com.stedu.controller;

import com.stedu.bean.RespBean;
import com.stedu.bean.Student;
import com.stedu.bean.Teacher;
import com.stedu.exception.SteduException;
import com.stedu.service.StudentOperateService;
import com.stedu.service.StudentService;
import com.stedu.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin//跨域问题
@RestController
@RequestMapping("/user/studentOperate")
public class StudentOperateController {
    @Autowired
    private StudentOperateService studentOperateService;
    @Autowired
    private StudentService studentService;

    //预约课程
    @PostMapping("/insertSidAndTid")
    public RespBean insertSidAndTid(@RequestBody Map<String, Object> map) {
        Integer sid = (Integer) map.get("sid");
        Integer tid = (Integer) map.get("tid");
        if (studentOperateService.insertSidAndTid(sid, tid)) {
            return RespBean.ok("预约成功");
        } else {
            return RespBean.error("预约失败，已经预约这门课了");
        }
    }

    //删除课程
    @DeleteMapping("/deleteSidAndTidBySidAndTid")
    public RespBean deleteSidAndTidBySidAndTid(@RequestParam("sid") Integer sid, @RequestParam("tid") Integer tid) {
        if (studentOperateService.deleteSidAndTidBySidAndTid(sid, tid)) {
            return RespBean.ok("取消预约成功");
        } else {
            return RespBean.error("取消预约失败，没有选这门课");
        }
    }

    //查询所有的老师课程信息
    @GetMapping("/selectAllTeacherAndCourse")
    public RespBean selectAllTeacherAndCourse() {
        List<Teacher> teacherList = studentOperateService.selectAllTeacherAndCourse();
        return RespBean.ok("", teacherList);
    }


    //展示学生的选择的老师课程的信息
    @GetMapping("/selectedTeacherAndCourse/{sno}")
    public RespBean selectedTeacherAndCourse(@PathVariable("sno") String sno) {
        List<Student> teacherList = studentOperateService.selectedTeacherAndCourse(sno);
        return RespBean.ok("", teacherList);
    }


    //后端接收并解析前端传来的jwt
    @GetMapping("/studentLoginInfo")
    public RespBean studentLoginInfo(@RequestHeader(value="token") String token) {
        //不需要获取jwt直接解析
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer sid = (Integer) map.get("sid");
        //通过id查询用户信息
        //从上层往下层定义方法，规定返回值类型
        Student student = studentOperateService.selectBySid(sid);
        return RespBean.ok("", student);
    }

    //修改学生密码
    @PutMapping("/update")
    public RespBean update(@RequestBody @Validated Student student) throws SteduException {
        //修改
        if (studentService.update(student)){
            return RespBean.ok("修改成功~~~");
        }
        else {
            return RespBean.error("修改失败，请重新修改");
        }
    }
}
